import Vue from "vue";
import Vuex from "vuex";

import { list } from "../data.js";
Vue.use(Vuex);

const actions = {};
const mutations = {
  //删除一个
  delOneGood(state, value) {
    state.list = state.list.filter((item) => item.id !== value);
  },
  //改变所有选项
  changeAll(state, value) {
    state.list.forEach((item) => {
      //这样list里面的每个的选中状态才会根据你传递过来的头部的全选按钮的状态变化
      item.select = value;
    });
  },
  //清空购物车
  clearAll(state) {
    state.list = [];
  },
  //删除选中项
  clearSelect(state) {
    state.list = state.list.filter((item) => !item.select);
  },
  //因为commit的时候你传的第一个参数是JIA所以函数名只能叫JIA
  //(state,payload)
  JIA(state, value) {
    //第一个参数就是state，第二个参数就是我们commit的时候丢过来的第二个参数
    // console.log("我是vuex里面的东西", a === state, b);
    state.sum += value;
  },
};
const state = {
  list,
};
const getters = {
  //list的长度
  total() {
    return state.list.length;
  },
  //已选数量
  selectTotal() {
    return state.list.reduce((item, prev) => (item += prev.select), 0);
  },
  //总价
  totalPrice(state) {
    return state.list
      .filter((item) => item.select)
      .reduce((item, prev) => (item += prev.buy_num * prev.price), 0);
  },
  //总数量
  totalNum(state) {
    return state.list
      .filter((item) => item.select)
      .reduce((item, prev) => (item += prev.buy_num), 0);
  },
};
//创建一个store

// const store = new Vuex.Store({
//   actions,
//   mutations,
//   state,
// });
// //暴露store
// export default store
export default new Vuex.Store({
  actions,
  mutations,
  state,
  getters,
});
